/*
	This file is part of "Ants on the web".

    "Ants on the web" is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    "Ants on the web" is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with "Ants on the web".  If not, see <http://www.gnu.org/licenses/>.
*/

package org.utc.ia04.antsontheweb.antColonyOptimisation.antColony;

import org.utc.ia04.antsontheweb.antColonyOptimisation.ant.AntAgent;
import org.utc.ia04.antsontheweb.pheromone.PheromoneManagerAgent;
import org.utc.ia04.antsontheweb.utilities.Requete;
import org.utc.ia04.antsontheweb.utilities.RequeteException;

import jade.core.Agent;
import jade.core.behaviours.TickerBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;

public class AntColonyBhv extends TickerBehaviour
{
	//serialVersionUID
	private static final long serialVersionUID = 8936191058659964608L;

	public AntColonyBhv(Agent a, long period)
	{
		super(a, period);
	}

	protected void onTick() 
	{
		//Traitements de tous les messages recus
		ACLMessage message = myAgent.receive();
		while (message != null)
		{
			String msgContent =  message.getContent();
			try
			{
				Requete query = Requete.deserialize_withException(msgContent, myAgent, message);
				System.out.println();
				switch(query.getType())
				{
					case Requete.GUI_ENDSIMULATION:
						askResult(message);
						myAgent.doDelete();
						block();
						break;
					case Requete.ANT_RESSOURCEPICKUP:
						((AntColonyAgent)myAgent).incRessourceCollectedNb();
						break;
					case Requete.ANT_DYING:
						((AntColonyAgent)myAgent).decAntNumber();
						break;
					default:
						System.out.println(myAgent.getName()+"received message:"+msgContent+"and not know how to treat it.");
						break;
				}
			}
			catch(RequeteException ex) { }
			message = myAgent.receive();
		}
		
		if (((AntColonyAgent)myAgent).getNbAntToCreate() > 0)
		{
			((AntColonyAgent)myAgent).createAnts();
		}
	
		if(((AntColonyAgent)myAgent).enougthCollectedResource())
		{
			askResult(message);
			myAgent.doDelete();
		}
		else
		{
			activateAllAnts();
		}
	}
	
	private void activateAllAnts()
	{
		ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);
		Requete query = new Requete(Requete.AC_GO,Long.toString(((AntColonyAgent)myAgent).getTickerTime()));
		msg.setContent(query.serialize());
		
		DFAgentDescription template = new DFAgentDescription();
		ServiceDescription sd = new ServiceDescription();
		sd.setType(AntAgent.DF_TYPE);
		template.addServices(sd);
		try
		{
			DFAgentDescription[] result = DFService.search(myAgent, template);
			for(int i = 0; i < result.length; ++i)
				msg.addReceiver(result[i].getName());
		}
		catch(Exception fe) 
		{
		System.out.println(fe.getMessage());	
		}
		myAgent.send(msg);
		((AntColonyAgent)myAgent).incTickerTime();
		
	}
	
	private void askResult(ACLMessage parReceivedMessage)
	{
		//TODO etudier searchUntilfound pour l'envoi de messages
			// recuperer exception de search
			// faire de l'envoie de msg par topic
			//probl�me avec cette fonction provoQUE EXCEPTION
		//DEBUG
		//System.out.println("IN ASKRESULT");
		ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);
		//msg.addReplyTo(parReceivedMessage.getSender());
		Requete query = new Requete(Requete.AC_ASKRESULT,"");
		msg.setContent(query.serialize());
		
		DFAgentDescription template = new DFAgentDescription();
		ServiceDescription sd = new ServiceDescription();
		sd.setType(PheromoneManagerAgent.dfType); //sd.setType(PheromoneManagerAgent.dfType); 
		template.addServices(sd);
		try
		{
			DFAgentDescription[] result = DFService.search(myAgent, template);
			for(int i = 0; i < result.length; ++i)
				msg.addReceiver(result[i].getName());
		}
		catch(Exception fe) {
			System.out.println(fe.getMessage());
		}
		myAgent.send(msg);
	}
}
